import { CraftingSystem } from './CraftingSystem';
import { CraftingGrid, CraftingResult } from './types';
import { BlockType } from '@/blocks/types';
import { Inventory } from '@/player/Inventory';

export class CraftingManager {
  private craftingSystem: CraftingSystem;
  private craftingGrid: CraftingGrid;
  private isOpen = false;

  constructor() {
    this.craftingSystem = new CraftingSystem();
    this.craftingGrid = this.createEmptyGrid(3); // 3x3 工作台网格
  }

  private createEmptyGrid(size: number): CraftingGrid {
    const grid: CraftingGrid = [];
    for (let row = 0; row < size; row++) {
      grid[row] = [];
      for (let col = 0; col < size; col++) {
        grid[row][col] = { type: null, count: 0 };
      }
    }
    return grid;
  }

  public openCraftingTable(): void {
    this.isOpen = true;
    this.clearGrid();
  }

  public closeCraftingTable(): void {
    this.isOpen = false;
    // 将未使用的材料返回到玩家物品栏
    this.returnMaterialsToInventory();
  }

  private returnMaterialsToInventory(): void {
    // 这个方法需要在实际游戏中实现
    // 现在先清空网格
    this.clearGrid();
  }

  public isOpenCraftingTable(): boolean {
    return this.isOpen;
  }

  public getCraftingGrid(): CraftingGrid {
    return this.craftingGrid;
  }

  public setGridSlot(row: number, col: number, type: BlockType | null, count: number): void {
    if (row >= 0 && row < this.craftingGrid.length && 
        col >= 0 && col < this.craftingGrid[row].length) {
      this.craftingGrid[row][col] = { type, count };
    }
  }

  public getGridSlot(row: number, col: number): { type: BlockType | null; count: number } | null {
    if (row >= 0 && row < this.craftingGrid.length && 
        col >= 0 && col < this.craftingGrid[row].length) {
      return this.craftingGrid[row][col];
    }
    return null;
  }

  public clearGrid(): void {
    for (let row = 0; row < this.craftingGrid.length; row++) {
      for (let col = 0; col < this.craftingGrid[row].length; col++) {
        this.craftingGrid[row][col] = { type: null, count: 0 };
      }
    }
  }

  public checkCurrentRecipe(): CraftingResult | null {
    return this.craftingSystem.checkRecipe(this.craftingGrid);
  }

  public executeCrafting(inventory: Inventory): boolean {
    const result = this.checkCurrentRecipe();
    if (!result) {
      return false;
    }

    return this.craftingSystem.executeRecipe(result.recipe, inventory, this.craftingGrid);
  }

  public getCraftingSystem(): CraftingSystem {
    return this.craftingSystem;
  }
}